package com.bauer.framework.autumn.utils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @Author ：rui.wei
 * @Date ：Created in 17:15 2018/8/6
 * @Description：
 */
public class AnnotationUtils {

    private static final String JAVA_LANG_PKG = "java.lang.annotation";


    /**
     * 找到bean上的注解
     *
     * @param targetClass bean的类型
     * @param annotationType 注解的类型
     */
    public static <A extends Annotation> A findAnnotationOnBean(Class targetClass,
            Class<A> annotationType) {
        Annotation[] annotations = targetClass.getAnnotations();

        for (Annotation annotation : annotations) {
            if (annotation.annotationType() == annotationType) {
                return (A) annotation;
            }
        }

        for (Annotation annotation : annotations) {

            //排除java自带注解
            if (annotation.annotationType().getName().startsWith(JAVA_LANG_PKG)) {
                continue;
            }

            return findAnnotationOnBean(annotation.annotationType(), annotationType);
        }

        return null;
    }

    /**
     * 获取方法上的注解
     */
    public static <A extends Annotation> A findAnnotationOnMethod(Method method,
            Class<A> annotationType) {

        Annotation[] annotations = method.getDeclaredAnnotations();
        for (Annotation annotation : annotations) {

            if (annotation.annotationType() == annotationType) {
                return (A) annotation;
            }
        }

        for (Annotation annotation : annotations) {

            //排除java自带注解
            if (annotation.annotationType().getName().startsWith(JAVA_LANG_PKG)) {
                continue;
            }

            Annotation finalAnnotation = findAnnotationOnBean(annotation.annotationType(),
                    annotationType);
            if (finalAnnotation != null) {
                return (A) finalAnnotation;
            }
        }
        return null;
    }

    public static <A extends Annotation> boolean hasAnnotation(Class targetClass,
            Class<A> annotationType) {
        return targetClass.isAnnotationPresent(annotationType);
    }


    /**
     * 根据名称判断是否是java内置的注解
     */
    public static boolean isJavaAnnotation(String className) {
        if (className == null) {
            return false;
        }
        return className.startsWith(JAVA_LANG_PKG);
    }
}
